<template>
  <el-config-provider :locale="zhCn">
    <div class="resignation-insert">
      <el-form 
        :model="form" 
        :rules="rules" 
        ref="formRef" 
        label-width="120px"
        v-loading="loading">
        <el-row :gutter="24">
          <el-col :span="24">
            <div class="grid-content ep-bg-purple-light" style="padding: 15px 0;">
              <el-form-item label="离职申请" label-position="top"
                :style="{ fontSize: '15px', fontWeight: 'bold', borderBottom: '1px dashed #e4e7ed' }">
                <div class="progress-bar">
                  <div class="progress"></div>
                </div>
              </el-form-item>
            </div>
          </el-col>
          
          <!-- 员工选择 -->
          <el-col :span="12">
            <div class="grid-content ep-bg-purple-light">
              <el-form-item label="选择员工" prop="employeeId" required>
                <el-select 
                  v-model="selectedEmployeeId"
                  placeholder="请选择员工"
                  style="width: 260px"
                  @change="handleEmployeeChange"
                  filterable
                  remote
                  :remote-method="searchEmployees"
                  :loading="employeeLoading">
                  <el-option
                    v-for="employee in employeeOptions"
                    :key="employee.employeeId"
                    :label="employee.employeeName"
                    :value="employee.employeeId">
                    <span style="float: left">{{ employee.employeeName }}</span>
                    <span style="float: right; color: #8492a6; font-size: 13px">{{ employee.employeeIdNumber }}</span>
                  </el-option>
                </el-select>
              </el-form-item>
            </div>
          </el-col>
          
          <el-col :span="12">
            <div class="grid-content ep-bg-purple-light">
              <el-form-item label="工号" prop="employeeIdNumber" required>
                <el-input v-model="form.employeeIdNumber" placeholder="请输入工号" style="width: 260px" disabled />
              </el-form-item>
            </div>
          </el-col>
          
          <el-col :span="12">
            <div class="grid-content ep-bg-purple-light">
              <el-form-item label="员工姓名" prop="employeeName" required>
                <el-input v-model="form.employeeName" placeholder="请输入员工姓名" style="width: 260px" disabled />
              </el-form-item>
            </div>
          </el-col>
          
          <el-col :span="12">
            <div class="grid-content ep-bg-purple-light">
              <el-form-item label="身份证号" prop="idCardNumber" required>
                <el-input v-model="form.idCardNumber" placeholder="请输入身份证号" style="width: 260px" disabled />
              </el-form-item>
            </div>
          </el-col>
          
          <el-col :span="12">
            <div class="grid-content ep-bg-purple-light">
              <el-form-item label="部门" prop="department" required>
                <el-input v-model="form.department" placeholder="请输入部门" style="width: 260px" disabled />
              </el-form-item>
            </div>
          </el-col>
          
          <el-col :span="12">
            <div class="grid-content ep-bg-purple-light">
              <el-form-item label="岗位" prop="position" required>
                <el-input v-model="form.position" placeholder="请输入岗位" style="width: 260px" disabled />
              </el-form-item>
            </div>
          </el-col>
          
          <el-col :span="12">
            <div class="grid-content ep-bg-purple-light">
              <el-form-item label="聘用形式" prop="employmentForm" required>
                <el-input v-model="form.employmentForm" placeholder="请输入聘用形式" style="width: 260px" disabled />
              </el-form-item>
            </div>
          </el-col>
          
          <el-col :span="12">
            <div class="grid-content ep-bg-purple-light">
              <el-form-item label="入职日期" prop="entryDate" required>
                <el-date-picker 
                  v-model="form.entryDate" 
                  type="date" 
                  placeholder="请选择入职日期"
                  value-format="YYYY-MM-DD"
                  style="width: 260px;"
                  disabled>
                </el-date-picker>
              </el-form-item>
            </div>
          </el-col>
          
          <el-col :span="12">
            <div class="grid-content ep-bg-purple-light">
              <el-form-item label="部门主管" prop="departmentHead" required>
                <el-input v-model="form.departmentHead" placeholder="请输入部门主管" style="width: 260px" />
              </el-form-item>
            </div>
          </el-col>
          
          <el-col :span="12">
            <div class="grid-content ep-bg-purple-light">
              <el-form-item label="经办HR" prop="handlingHr" required>
                <el-input v-model="form.handlingHr" placeholder="请输入经办HR" style="width: 260px" />
              </el-form-item>
            </div>
          </el-col>
          
          <el-col :span="12">
            <div class="grid-content ep-bg-purple-light">
              <el-form-item label="预计离职日期" prop="expectedResignationDate" required>
                <el-date-picker 
                  v-model="form.expectedResignationDate" 
                  type="date" 
                  placeholder="请选择预计离职日期"
                  value-format="YYYY-MM-DD"
                  style="width: 260px;">
                </el-date-picker>
              </el-form-item>
            </div>
          </el-col>
          
          <el-col :span="12">
            <div class="grid-content ep-bg-purple-light">
              <el-form-item label="离职原因" prop="reasonForResignation" required>
                <el-input 
                  v-model="form.reasonForResignation" 
                  type="textarea" 
                  placeholder="请输入离职原因"
                  :rows="2" 
                  style="width: 260px" />
              </el-form-item>
            </div>
          </el-col>
          
          <el-col :span="12">
            <div class="grid-content ep-bg-purple-light">
              <el-form-item label="工作交接人" prop="workHandoverPerson">
                <el-input v-model="form.workHandoverPerson" placeholder="请输入工作交接人" style="width: 260px" />
              </el-form-item>
            </div>
          </el-col>
          
          <el-col :span="12">
            <div class="grid-content ep-bg-purple-light">
              <el-form-item label="工作交接确认" prop="workHandoverConfirmation">
                <el-select v-model="form.workHandoverConfirmation" placeholder="请选择" style="width: 260px">
                  <el-option label="已确认" value="已确认" />
                  <el-option label="未确认" value="未确认" />
                </el-select>
              </el-form-item>
            </div>
          </el-col>
          
          <el-col :span="12">
            <div class="grid-content ep-bg-purple-light">
              <el-form-item label="财务交接确认" prop="financialHandoverConfirmation">
                <el-select v-model="form.financialHandoverConfirmation" placeholder="请选择" style="width: 260px">
                  <el-option label="已确认" value="已确认" />
                  <el-option label="未确认" value="未确认" />
                </el-select>
              </el-form-item>
            </div>
          </el-col>
          
          <el-col :span="12">
            <div class="grid-content ep-bg-purple-light">
              <el-form-item label="行政交接确认" prop="administrativeHandoverConfirmation">
                <el-select v-model="form.administrativeHandoverConfirmation" placeholder="请选择" style="width: 260px">
                  <el-option label="已确认" value="已确认" />
                  <el-option label="未确认" value="未确认" />
                </el-select>
              </el-form-item>
            </div>
          </el-col>
          
          <el-col :span="12">
            <div class="grid-content ep-bg-purple-light">
              <el-form-item label="人事交接确认" prop="personnelHandoverConfirmation">
                <el-select v-model="form.personnelHandoverConfirmation" placeholder="请选择" style="width: 260px">
                  <el-option label="已确认" value="已确认" />
                  <el-option label="未确认" value="未确认" />
                </el-select>
              </el-form-item>
            </div>
          </el-col>
          
          <el-col :span="12">
            <div class="grid-content ep-bg-purple-light">
              <el-form-item label="正式离职日期" prop="officialResignationDate">
                <el-date-picker 
                  v-model="form.officialResignationDate" 
                  type="date" 
                  placeholder="请选择正式离职日期"
                  value-format="YYYY-MM-DD"
                  style="width: 260px;">
                </el-date-picker>
              </el-form-item>
            </div>
          </el-col>
          
          <el-col :span="12">
            <div class="grid-content ep-bg-purple-light">
              <el-form-item label="HR确认" prop="hrConfirmation">
                <el-select v-model="form.hrConfirmation" placeholder="请选择" style="width: 260px">
                  <el-option label="已确认" value="已确认" />
                  <el-option label="未确认" value="未确认" />
                </el-select>
              </el-form-item>
            </div>
          </el-col>
          
          <el-col :span="12">
            <div class="grid-content ep-bg-purple-light">
              <el-form-item label="申请日期" prop="applicationDate" required>
                <el-date-picker 
                  v-model="form.applicationDate" 
                  type="date" 
                  placeholder="请选择申请日期"
                  value-format="YYYY-MM-DD"
                  style="width: 260px;">
                </el-date-picker>
              </el-form-item>
            </div>
          </el-col>
        </el-row>
        
        <hr>
        <el-form-item style="margin-top: 20px; text-align: center;">
          <el-button @click="cancel">取消</el-button>
          <el-button type="primary" @click="submitForm" :loading="submitLoading">提交</el-button>
        </el-form-item>
      </el-form>
    </div>
  </el-config-provider>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import zhCn from 'element-plus/es/locale/lang/zh-cn'
import server from '@/api/request'

const emit = defineEmits(['added', 'close'])

// 表单引用
const formRef = ref()

// 表单数据
const form = reactive({
  employeeId: null,             
  employeeIdNumber: '',         
  employeeName: '',             
  idCardNumber: '',             
  department: '',               
  position: '',                 
  employmentForm: '',           
  entryDate: '',                
  departmentHead: '',          
  handlingHr: '',               
  expectedResignationDate: '',  
  reasonForResignation: '',     
  workHandoverPerson: '',       
  workHandoverConfirmation: '', 
  financialHandoverConfirmation: '', 
  administrativeHandoverConfirmation: '', 
  personnelHandoverConfirmation: '',     
  officialResignationDate: '',          
  hrConfirmation: '',                    
  applicationDate: ''                  
})

// 员工选择相关
const selectedEmployeeId = ref('')
const employeeOptions = ref([])
const employeeLoading = ref(false)

// 表单验证规则
const rules = {
  employeeId: [{ required: true, message: '请选择员工', trigger: 'change' }], // 修改验证字段
  employeeIdNumber: [{ required: true, message: '请输入工号', trigger: 'blur' }],
  employeeName: [{ required: true, message: '请输入员工姓名', trigger: 'blur' }],
  idCardNumber: [{ required: true, message: '请输入身份证号', trigger: 'blur' }],
  department: [{ required: true, message: '请输入部门', trigger: 'blur' }],
  position: [{ required: true, message: '请输入岗位', trigger: 'blur' }],
  employmentForm: [{ required: true, message: '请输入聘用形式', trigger: 'blur' }],
  entryDate: [{ required: true, message: '请选择入职日期', trigger: 'change' }],
  departmentHead: [{ required: true, message: '请输入部门主管', trigger: 'blur' }],
  handlingHr: [{ required: true, message: '请输入经办HR', trigger: 'blur' }],
  expectedResignationDate: [{ required: true, message: '请选择预计离职日期', trigger: 'change' }],
  reasonForResignation: [{ required: true, message: '请输入离职原因', trigger: 'blur' }],
  applicationDate: [{ required: true, message: '请选择申请日期', trigger: 'change' }]
}

// 加载状态
const loading = ref(false)
const submitLoading = ref(false)

// 搜索员工
const searchEmployees = async (query) => {
  employeeLoading.value = true
  try {
    const response = await server.get('/into/findPage', {
      params: {
        pageNum: 1,
        pageSize: 20,
        ...(query ? { keyword: query } : {})
      }
    })
    
    if (response.code === 200) {
      employeeOptions.value = response.data.records
    }
  } catch (error) {
    console.error('获取员工列表失败:', error)
    ElMessage.error('获取员工列表失败')
  } finally {
    employeeLoading.value = false
  }
}

// 员工选择变化时更新表单
const handleEmployeeChange = (employeeId) => {
  const selectedEmployee = employeeOptions.value.find(emp => emp.employeeId === employeeId)
  if (selectedEmployee) {
    form.employeeId = employeeId
    form.employeeIdNumber = selectedEmployee.employeeIdNumber
    form.employeeName = selectedEmployee.employeeName
    form.idCardNumber = selectedEmployee.employeeNumber
    form.department = selectedEmployee.onboardingDepartment
    form.position = selectedEmployee.entryPosition
    form.employmentForm = selectedEmployee.employmentForm
    form.entryDate = selectedEmployee.dateOfInduction
    form.departmentHead = selectedEmployee.departmentHead || ''
  }
}

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid) => {
    if (valid) {
      if (!form.employeeId) {
        ElMessage.error('请选择员工')
        return
      }
      
      submitLoading.value = true
      try {
        const response = await server.post('/resignation/add', form)
        if (response.code === 200) {
          ElMessage.success('添加成功')
          emit('added')
        } else {
          ElMessage.error('添加失败: ' + response.message)
        }
      } catch (error) {
        console.error('添加失败:', error)
        ElMessage.error('添加失败: ' + (error.response?.data?.message || error.message))
      } finally {
        submitLoading.value = false
      }
    }
  })
}

// 取消操作
const cancel = () => {
  emit('close')
}

// 初始化获取员工列表
onMounted(() => {
  searchEmployees('')
})
</script>

<style scoped>
.resignation-insert {
  padding: 20px;
}

.progress-bar {
  height: 6px;
  background-color: #ccebf7;
  border-radius: 3px;
  display: flex;
  width: 100%;
  overflow: hidden;
}

.progress {
  width: 8%;
  height: 10;
  background-color: #61c3ea;
  border-radius: 3px 0 0 3px;
  transition: width 0.3s ease;
}
</style>